# -*- coding:utf-8 -*-

"""
TODO:
    1. 中间件方法 写成 独立的方法或者类 单独放到一个文件夹
       有 request 基类调用

       配置文件中，管理特定中间件的 开闭
"""

from tornado.web  import RequestHandler

from configure    import config

from utils.tokens import token_de
from utils.errors import errs

from loog.mylog   import flogger as logger


class BaseWebHandler(RequestHandler):
    """ web基类
    *主页 index.html
    """

    def prepare(self):
        value = self.get_secure_cookie(config.COOKIE_KEY)
        #logger.info('get cookie, value =', value, caller=self)
        if value != config.COOKIE_VALUE:
            self.render('login.html')

    def head(self, *args, **kwargs):
        self.write_error(404)

    def get(self, *args, **kwargs):
        self.write_error(404)

    def post(self, *args, **kwargs):
        self.write_error(404)

    def delete(self, *args, **kwargs):
        self.write_error(404)

    def patch(self, *args, **kwargs):
        self.write_error(404)

    def put(self, *args, **kwargs):
        self.write_error(404)


class BaseWebHandlerV2(RequestHandler):
    """ Handler 基类 """

    def prepare(self):

        logger.info('i am going...')

    def on_finish(self):

        pass

    def write(self, res):

        if isinstance(res, dict):
            if res.get('code'):
                res['msg'] = errs[res['code']]

        super(BaseWebHandlerV2, self).write(res)


class AuthHandler(BaseWebHandlerV2):
    """ 验证 登录/用户 权限 """

    def prepare(self):

        super(AuthHandler, self).prepare()

        req = self.request

        # 验证token
        if config.TOKEN_AUTH_SWITCH:
            token = req.headers.get('Token', '')
            token_status, token_data = token_verify(token)

            if not token_status:
                self.write(token_data)
                self.finish()
                return

            # 写token数据到header中供视图使用
            req.headers['TData'] = token_data


def token_verify(token):
    ''' 验证 token

    验证结果:
        1. 正常可用 True,  200
        2. 过期     False, 10002
        3. 错误     False, 401
    '''

    res     = {}
    de_data = {}
    de_data, err_code = token_de(
        token,
        config.JWT_SECRET,
        config.JWT_ALGORITHM,
        config.JWT_OPTIONS
    )
    if not de_data:
        logger.info('AUTH_ERROR')
        res['code'] = err_code
        return False, res

    return True, de_data


